//
//  GKUtils.m
//  Gainko
//
//  Created by jinfeng gu on 12-11-1.
//  Copyright (c) 2012年 RanCheng.gu. All rights reserved.
//

#import "GKUtils.h"


@implementation GKUtils


+(NSString*) saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath{
    
    if ([[extension lowercaseString] isEqualToString:@"png"]) {
        NSString *path = [directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"png"]];
        [UIImagePNGRepresentation(image) writeToFile:path options:NSAtomicWrite error:nil];
        return path;
        
    } else if ([[extension lowercaseString] isEqualToString:@"jpg"] || [[extension lowercaseString] isEqualToString:@"jpeg"]) {
        NSString *path = [directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"jpg"]];
        [UIImageJPEGRepresentation(image, 1.0) writeToFile:path options:NSAtomicWrite error:nil];
        return path;
    } else {
        //ALog(@"Image Save Failed\nExtension: (%@) is not recognized, use (PNG/JPG)", extension);
        return nil;
    }
}

+(NSString*) saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension{
    
    NSString *directoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    if ([[extension lowercaseString] isEqualToString:@"png"]) {
         NSString *path = [directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"png"]];
        [UIImagePNGRepresentation(image) writeToFile:path options:NSAtomicWrite error:nil];
        
        return path;
    } else if ([[extension lowercaseString] isEqualToString:@"jpg"] || [[extension lowercaseString] isEqualToString:@"jpeg"]) {
        
         NSString *path = [directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"jpg"]];
        [UIImageJPEGRepresentation(image, 1.0) writeToFile:path options:NSAtomicWrite error:nil];
        return path;
    } else {
        //ALog(@"Image Save Failed\nExtension: (%@) is not recognized, use (PNG/JPG)", extension);
        NSLog(@"文件后缀不认识");
        return nil;
    }
}

+(UIImage *) loadImage:(NSString *)fileName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
    UIImage * result = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.%@", directoryPath, fileName, extension]];
    
    return result;
}

+(UIImage *) loadImage:(NSString *)fileName ofType:(NSString *)extension {
    
    NSString *directoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    UIImage * result = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.%@", directoryPath, fileName, extension]];
    
    return result;
}

+(id)readPlist:(NSString *)fileName {
    NSData *plistData;
    NSString *error;
    NSPropertyListFormat format;
    id plist;
    
    NSString *localizedPath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"plist"];
    plistData = [NSData dataWithContentsOfFile:localizedPath];
    
    plist = [NSPropertyListSerialization propertyListFromData:plistData mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&error];
    if (!plist) {
        NSLog(@"Error reading plist from file '%s', error = '%s'", [localizedPath UTF8String], [error UTF8String]);
    }
    
    return plist;
}

+(id)readRTFDoc:(NSString*)fileName {
    NSData *docData;
    
    NSString *localizedPath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"rtf"];
    docData = [NSData dataWithContentsOfFile:localizedPath];
    NSString * doc =[[NSString alloc] initWithData:docData encoding:NSUTF8StringEncoding];
    return doc;
}

+(NSString*)convertDateToString:(NSDate*)date{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
    NSString *stringFromDate = [formatter stringFromDate:date];
    
    return stringFromDate;
}

+(NSArray*)parseThumbUrl:(NSString*)url
{
   NSArray *elements = [url componentsSeparatedByString:@"_"];
   
    return elements;
}

+(NSArray *)parseCityStateZip:(NSString *) searchText
{
    NSString * city = @"";
    NSString * state = @"";
    NSString * zip = @"";
    
    NSArray *location = [searchText componentsSeparatedByString:@","];
	NSArray *toReturn = nil;
    
    if ([location count] == 1) {
        // let trim the string before validating it
        zip = [[location objectAtIndex:0] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        
        // Verify with REGEX if the string is a zip code
        NSError *error = NULL;
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^\\d{5}$"
                                                                               options:NSRegularExpressionCaseInsensitive
                                                                                 error:&error];
        NSUInteger numberOfMatches = [regex numberOfMatchesInString:zip
                                                            options:0
                                                              range:NSMakeRange(0, [zip length])];
        
        if (numberOfMatches == 1) {
            toReturn = [NSArray arrayWithObjects:zip, nil];
        }
    } else if ([location count] == 2) {
        city = [[location objectAtIndex:0] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        state = [[location objectAtIndex:1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        
        toReturn = [NSArray arrayWithObjects:city, state, nil];
        
    }
    
    return toReturn;
}

+ (NSString *)stringFromDate:(NSDate *)date withFormat:(NSString*)format{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    //zzz表示时区，zzz可以删除，这样返回的日期字符将不包含时区信息 +0000。
    
    //[dateFormatter setDateFormat:@"yyyy-MM-dd EEEE HH:mm:ss zzz"];
    
    [dateFormatter setDateFormat:format];
    
    NSString *destDateString = [dateFormatter stringFromDate:date];
    return destDateString;
}

+ (NSDate *)dateFromString:(NSString *)dateString withFormat:(NSString*)format{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat: format];
    NSDate *destDate= [dateFormatter dateFromString:dateString];
    
    return destDate;
}


+(CGSize)calcSizeFromSting:(NSString*)str boundingRectWithSize:(CGSize)size andFont:(UIFont*)font
{
    
    NSAttributedString *attributedText = [[NSAttributedString alloc]initWithString:str attributes:@{
                                                                                                    NSFontAttributeName:font}];
    CGRect rect = [attributedText boundingRectWithSize:size
                                               options:NSStringDrawingUsesLineFragmentOrigin
                                               context:nil];
    
    CGSize labelsize = rect.size;
    
    return labelsize;
}


+(NSMutableAttributedString *)setTitleTextWithText:(NSString*)text sepcialText:(NSString *)specialText publicColor:(UIColor*)publicColor specialColor:(UIColor*)specialColor{
     NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:text];
     NSRange range = [text rangeOfString:specialText];
     [attrStr addAttribute:NSForegroundColorAttributeName value:KAPPMAINBLUECOLOR range:range];
     [attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(range.length, text.length - range.length)];
    return attrStr;
}

+(NSString *)getNumberIntWithNum:(NSNumber *)number{
    NSString *str;
    if (number == nil) {
        str = @"0";
    }else{
        str = [number stringValue];
    }
    return str;
}
+(NSString *)getNumberFloatWithNum:(NSNumber *)number{
    NSString *str;
    if (number == nil) {
        str = @"0.0";
    }else{
        str = [number stringValue];
    }
    return str;
}

+(NSString *)decodeDateNumber:(NSNumber *)num{
    NSString *dateStr;
    NSDate *publishDate = [NSDate dateWithTimeIntervalSince1970:[num longLongValue]/1000];
    dateStr = [GKUtils stringFromDate:publishDate withFormat:@"yyyy-MM-dd HH:mm"];
    return dateStr;
}
@end
